// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  switch (event.action) {
    case 'getXinJianByStatus': {
      return getXinJianByStatus(event)
    }
    case 'getAllOrderByOpenid': {
      return getAllOrderByOpenid(event)
    }
    case 'getAllOrderByStatus': {
      return getAllOrderByStatus(event)
    }
    case 'getCommentStatus': {
      return getCommentStatus(event)
    }



    default: {
      return
    }
  }
}

async function getXinJianByStatus(event) {
  const {
    OPENID
  } = cloud.getWXContext()
  try {
    return await db.collection("xinjian").where({
      shouJianRenOpenid: OPENID
    })
    .orderBy('chuangJianShiJiang', 'desc')
    .limit(6)
    .get()
  } catch (e) {
    console.error(e)
  }
}

async function getCommentStatus(event) {
  const {
    OPENID
  } = cloud.getWXContext()
  
  try {
    return await db.collection('huaticomment').aggregate()
    .lookup({
      from: 'huati',
      localField: 'huaTiId',
      foreignField: '_id',
      as: 'commentList'
    })
    .match({
      huaTiId:event.huaTiId,
      _openid:OPENID
    })
    .end()
  } catch (e) {
    console.error(e)
  }
}

